import getShortcutByName from "./getShortcutByName";
import {decodeURIWrapper} from "../../util";

const fetchHighlightComments = async (name: string, highlightId: string) => {
  const data = await getShortcutByName(name);
  if (!data.shortcut) {
    return;
  }
  const shortcut = data.shortcut;
  if (!shortcut.comments || shortcut.comments.trim() === "") return;
  const highlightViewstates = shortcut.comments.trim().split("\n\n");
  let viewstateFounds = highlightViewstates.filter((item: string) => {
    const [itemHighlightId] = item.split(";;").slice(0);
    return itemHighlightId === highlightId;
  });
  if (viewstateFounds.length !== 1){
    throw Error(`error: found more than 1 viewstate with highlightId: ${highlightId}`);
  }
  const viewstateFound = viewstateFounds[0];
  const [comments] = viewstateFound.split(";;").slice(-1);
  return decodeURIWrapper(comments).replaceAll("\n", "\n > ");
}

export default fetchHighlightComments;
